package com.atgugu.flink.chapter07.timer;

import com.atgugu.flink.bean.WaterSensor;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * @Author lzc
 * @Date 2022/4/6 10:02
 */
public class Flink02_Timer_EventTime {
    public static void main(String[] args) throws Exception {
        
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 10000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        // 当水位超过20的时候, 5s之后发出预警
        env
            .socketTextStream("hadoop162", 9999)
            .map(line -> {
                String[] data = line.split(",");
                return new WaterSensor(data[0], Long.valueOf(data[1]), Integer.valueOf(data[2]));
            })
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((ws, ts) -> ws.getTs())
            
            )
            .keyBy(WaterSensor::getId) // 如果要用定时器, 必须先keyBy 因为定时器是和key相关
            .process(new KeyedProcessFunction<String, WaterSensor, String>() {
                
                private long ts;
                
                // 当定时器触发的执行这个方法
                @Override
                public void onTimer(long timestamp,  // 定时器触发的时间
                                    OnTimerContext ctx,
                                    Collector<String> out) throws Exception {
                    out.collect(ctx.getCurrentKey() + " 水位超过 20, 发出预警信息...");
                }
                
                @Override
                public void processElement(WaterSensor value,
                                           Context ctx,
                                           Collector<String> out) throws Exception {
                    
                    if (value.getVc() > 20) {
                        long ts = value.getTs() + 5000;
                        ctx.timerService().registerEventTimeTimer(ts);
                    } else if (value.getVc() == 10) {
                    
                    }
                    
                    
                }
            })  // 定时器只能用在process中, 因为这里才有context
            .print();
        
        
        env.execute("flink_timer");
        
        
    }
}
